package seatiger.tomcat.catalina.connector;

import seatiger.tomcat.catalina.Constants;
import seatiger.tomcat.catalina.Request;
import seatiger.tomcat.util.StringManager;

import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;
@Deprecated
public class RequestStream extends ServletInputStream {
    //这里就是 SocketInputStream
    private InputStream stream;
    //已经读取到的总数
    private int count;
    //需要读取的总数
    private int length;

    /**
     * 连接是否已关闭
     */
    protected boolean closed = false;

    protected static StringManager sm = StringManager.getManager(Constants.PACKAGE_CONNECTOR);

    public RequestStream(InputStream inputStream, int length) {
        this.stream = inputStream;
        this.length = length;
        this.count = 0;
    }
    public RequestStream(Request request){
        this.closed = false;
        this.count = 0;
        this.stream =request.getStream();
        this.length = request.getRequest().getContentLength();
    }


    @Override
    public int read() throws IOException {
        if (length >= 0 && count >= length){
            return -1;
        }
        //从SocketInputStream 中读取数据
        int b = stream.read();
        if (b >= 0){
            count++;
        }
        return b;
    }

    @Override
    public int read(byte[] b, int off, int len) throws IOException {
        int toRead =len;
        if (length > 0){
            //数据已经读完了
            if (count >= length){
                return -1;
            }
            if (count + len > length){
                toRead =length - count;
            }
        }
        int actuallyRead = super.read(b, off, toRead);
        return actuallyRead;
    }

    @Override
    public int read(byte[] b) throws IOException {
        return read(b,0,b.length);
    }

    @Override
    public void close() throws IOException {
        if (closed){
            throw new IOException(sm.getString("requestStream.close.closed"));
        }
        if (length > 0){
            while (count < length) {
                int b = read();
                if (b < 0){
                    break;
                }
            }
        }
        closed = true;
    }
}
